package cn.white.ymc.mvvmmaster.data.util;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;

import cn.white.ymc.mvvmmaster.data.api.ApiStore;
import cn.white.ymc.mvvmmaster.data.api.RetrofitFactory;
import cn.white.ymc.mvvmmaster.data.bean.UserInfo;
import cn.white.ymc.mvvmmaster.data.local.LocalUserDataSource;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * retofit liveData 工具类
 *
 * @packageName: cn.white.ymc.mvvmdemo.data.util
 * @fileName: UserInfoRepository
 * @date: 2018/11/5  17:18
 * @author: ymc
 * @QQ:745612618
 */

public class UserInfoRepository {

    private static final UserInfoRepository instance = new UserInfoRepository();

    public static UserInfoRepository getInstance() {
        return instance;
    }

    private ApiStore apiStore = RetrofitFactory.getInstance().create(ApiStore.class);

    public LiveData<UserInfo> getUser(String username) {
        final MutableLiveData<UserInfo> user = new MutableLiveData<>();
        apiStore.queryUserByUsername(username)
                .enqueue(new Callback<UserInfo>() {
                    @Override
                    public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                        user.setValue(response.body());
                        // update cache
                        LocalUserDataSource.getInstance().addUser(response.body());
                    }

                    @Override
                    public void onFailure(Call<UserInfo> call, Throwable t) {

                    }
                });
        return user;
    }

}
